package org.sean.generator.service;

import com.github.pagehelper.PageHelper;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.sean.generator.form.Page;
import org.sean.generator.form.Query;
import org.sean.generator.mapper.GeneratorMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器
 */
@Service
public class GeneratorService {
    @Autowired
    private GeneratorMapper generatorMapper;
    @Autowired
    private CodeService codeService;

    public Page queryList(Query query) {
        com.github.pagehelper.Page page = PageHelper.startPage(query.getPage(), query.getLimit());
        List<Map<String, Object>> list = generatorMapper.queryList(query);

        return new Page(list, (int) page.getTotal(), query.getLimit(), query.getPage());
    }

    public Map<String, String> queryTable(String tableName) {
        return generatorMapper.queryTable(tableName);
    }

    public List<Map<String, String>> queryColumns(String tableName) {
        return generatorMapper.queryColumns(tableName);
    }

    /**
     * 生成代码
     *
     * @param includeFc  包含框架
     * @param groupId    groupId
     * @param artifactId artifactId
     * @param tableNames tableNames
     * @param tp         表前缀
     * @return 代码源码
     */
    public byte[] generatorCode(boolean includeFc, String groupId, String artifactId, String[] tableNames, String tp) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        String version = null;
        if (includeFc) {
            codeService.generatorCode(tp, version, groupId, artifactId, null, null, zip);
        }


        for (String tableName : tableNames) {
            //查询表信息
            Map<String, String> table = queryTable(tableName);
            //查询列信息
            List<Map<String, String>> columns = queryColumns(tableName);
            //生成代码
            codeService.generatorCode(tp, version, groupId, artifactId, table, columns, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }
}
